/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.utils.URLUtils;
import Model.Client;
import Model.acl.ACL;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Anthares
 */
public class ACLFilter implements Filter {
    private static final boolean debug = true;
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 

    private FilterConfig filterConfig = null;

    public ACLFilter() {
    }

    /**
     *
     * @param request  The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain    The filter chain we are processing
     *
     * @exception IOException      if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        String requestedRessource = URLUtils.getRequestedURI(req, getFilterConfig().getServletContext());
        log("Asking for " + requestedRessource);
        if(ACL.hasRessource(requestedRessource)){
            HttpSession session = req.getSession(false);
            if(session == null || session.getAttribute("user") == null){
                log("as guest");
                if(!ACL.hasAccess(requestedRessource, "guest")){
                    request.setAttribute("status", null);
                    request.getRequestDispatcher("/login").forward(request, response);
                    return;
                }
            } else {
                Client user = (Client) session.getAttribute("user");
                log("as role : " + user.getRole());
                if(!ACL.hasAccess(requestedRessource, user.getRole())){
                    request.setAttribute("errorCode", 403);
                    request.getRequestDispatcher("/error.jsp").forward(request, response);
                    return;
                }
            }
        } else {
            log(requestedRessource + " not found");
            request.setAttribute("errorCode", 404);
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter
     */
    public void destroy() {
    }

    /**
     * Init method for this filter
     */
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        if(filterConfig != null){
            if(debug){
                log("ACLFilter:Initializing filter");
            }
        }
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if(filterConfig == null){
            return ("ACLFilter()");
        }
        StringBuffer sb = new StringBuffer("ACLFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }

    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try{
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
        } catch(Exception ex){
        }
        return stackTrace;
    }

    public void log(String msg) {
        filterConfig.getServletContext().log(msg);
    }
}
